package com.example.demo.netty.socket;

import com.example.demo.demoApi.NettyExecutor;
import com.example.demo.netty.AbstractServerHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * Socket API
 */
@Slf4j
public class SocketServerHandler extends AbstractServerHandler {

    public SocketServerHandler(NettyExecutor apiExecutor) {
        this.apiExecutor = apiExecutor;
    }
    @Override
    protected void initChannel(SocketChannel ch) {
        // 添加自定义编码器
        ch.pipeline().addLast(new MyMessageEncoder(StandardCharsets.UTF_8));
        // 添加自定义解码器
        ch.pipeline().addLast(new SocketMessageDecoder(StandardCharsets.UTF_8));
        ch.pipeline().addLast("handler", new SocketAPIChannelHandler());

        log.info("Socket API - a connection is ready. SocketChannel:{}", ch);
    }

    /**
     * 消息Handler，用于处理被动的消息请求
     */
    private class SocketAPIChannelHandler extends SimpleChannelInboundHandler<String> {
        @Override
        public void channelRead0(ChannelHandlerContext ctx, String message) {

            ctx.writeAndFlush(message);
            //
//            AbstractMsg msg = apiExecutor.parseToMsg(frame);
//
//            // 处理信息
//            AbstractMsg respMsg = apiExecutor.execute(msg, APIProtocolType.SOCKET, NettyUtil.getNetAddress(ctx).toString());
//
//            // 给客户端发响应信息
//            SocketServerHandler.super.sendSocketMsg(ctx, respMsg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
            log.error("exceptionCaught: ctx:{}, cause:{}", ctx, cause);
        }

    }

}
